<template>
	<div>
		<headerTop></headerTop>
		<div class="table-container">
		<el-table
		    :data="tableData"
		    style="width: 100%;margin: 0 auto;border: 1px solid #dfe6ec;"
			:header-cell-style="header">
		    <el-table-column type="expand">
		      <template slot-scope="props">
		        <el-form label-position="left" inline class="demo-table-expand">
		          <el-form-item label="店铺名称">
		            <span>{{ props.row.name }}</span>
		          </el-form-item>
		          <el-form-item label="店铺地址">
		            <span>{{ props.row.address }}</span>
		          </el-form-item>
		          <el-form-item label="店铺介绍">
		            <span>{{ props.row.description }}</span>
		          </el-form-item>
		          <el-form-item label="店铺 ID">
		            <span>{{ props.row.id }}</span>
		          </el-form-item>
		          <el-form-item label="联系电话">
		            <span>{{ props.row.phone }}</span>
		          </el-form-item>
		          <el-form-item label="评分">
		            <span>{{ props.row.rating }}</span>
		          </el-form-item>
		          <el-form-item label="销售量">
		            <span>{{ props.row.recent_order_num }}</span>
		          </el-form-item>
				  <el-form-item label="分类">
				    <span>{{ props.row.category }}</span>
				  </el-form-item>
		        </el-form>
		      </template>
		    </el-table-column>
		    <el-table-column
			header-align="center"
			align="center"
		      label="店铺名称"
		      prop="name"
			  width="200">
		    </el-table-column>
		    <el-table-column
			header-align="center"
			align="center"
		      label="店铺地址"
		      prop="address"
			  width="400">
		    </el-table-column>
			<el-table-column
			header-align="center"
			align="center"
			  label="店铺介绍"
			  prop="description"
			  width="200">
			</el-table-column>
		    <el-table-column header-align="center" align="center" label="操作" width="400">
				<template slot-scope="scope">
				        <el-button
				          size="mini"
				          @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
				        <el-button
				          size="mini" @click="addFood(scope.$index, scope.row)">添加食品</el-button>
						  <el-button
						    size="mini"
						    type="danger"
							@click="handleDelete(scope.$index, scope.row)">删除</el-button>
				      </template>
		    </el-table-column>
		  </el-table>
		  </div>
		  <div class="Pagination" style="text-align: left;margin-top: 10px;margin-left: 30px;">
		      <el-pagination
		        @current-change="handleCurrentChange"
		        :current-page="currentPage"
				:page-size="20"
		        layout="total, prev, pager, next"
		        :total="count">
		      </el-pagination>
		  </div>
		  <el-dialog title="修改店铺信息" :visible.sync="dialogFormVisible">
		    <el-form ref="form" :model="selectTable">
		      <el-form-item label="店铺名称" label-width="100px">
		        <el-input v-model="selectTable.name"></el-input>
		      </el-form-item>
		      <el-form-item label="详细地址" label-width="100px">
		        <el-autocomplete
		          v-model="address.address"
		          :fetch-suggestions="querySearchAsync"
		          placeholder="请输入地址"
		          style="width: 100%;"
		          @select="addressSelect"
		        ></el-autocomplete>
				<span>当前城市:{{city.name}}</span>
		      </el-form-item>
		      <el-form-item label="店铺介绍" label-width="100px">
		        <el-input v-model="selectTable.description"></el-input>
		      </el-form-item>
		      <el-form-item label="联系电话" label-width="100px">
		        <el-input v-model="selectTable.phone"></el-input>
		      </el-form-item>
		      <el-form-item label="店铺分类" label-width="100px">
		          <el-cascader
		            :options="categoryOptions"
		            v-model="selectedCategory"
					:props="{ checkStrictly: true }"
		          ></el-cascader>
		      </el-form-item>
		     <el-form-item label="商铺图片" label-width="100px">
		         <el-upload
		           class="avatar-uploader"
		           :action="baseUrl + '/v1/addimg/shop'"
		           :show-file-list="false"
		           :on-success="handleAvatarSuccess"
		           :before-upload="beforeAvatarUpload">
		           <img v-if="selectTable.image_path" :src="baseImgpath + selectTable.image_path" class="avatar">
		           <i v-else class="el-icon-plus avatar-uploader-icon"></i>
		         </el-upload>
		     </el-form-item>
			  <el-form-item>
			     <el-button type="primary" @click="onSubmit">立即创建</el-button>
			     <el-button @click="dialogFormVisible = false">取消</el-button>
			   </el-form-item>
		    </el-form>
		  </el-dialog>
	</div>
	
	
</template>

<script>
	import headerTop from '../../../components/headerTop.vue'
	import {baseUrl,baseImgpath} from '../../../config/url.js'
	import {cityGuess, getResturants, getResturantsCount, foodCategory, updateResturant, searchplace, deleteResturant} from '../../../api/getData.js'
	export default{
		data(){
			return{
				baseUrl,
				baseImgpath,
				dialogFormVisible: false,
				header:{'background-color': '#eef1f6'},
				currentPage: 1, // 当前页码
				pageSize: 10, // 每页的数据条数
				city: {},
				offset: 0,
				limit: 20,
				count: 1,
				selectTable: {},
				address: {address: ''},
				categoryOptions: [],
				selectedCategory:[],
				form: {
				          name: '',
				          region: '',
				          date1: '',
				          date2: '',
				          delivery: false,
				          type: [],
				          resource: '',
				          desc: ''
				},
				 tableData: [{
				          id: '12987122',
				          name: '好滋好味鸡蛋仔',
				          category: '江浙小吃、小吃零食',
				          desc: '荷兰优质淡奶，奶香浓而不腻',
				          address: '上海市普陀区真北路',
				          shop: '王小虎夫妻店',
				          shopId: '10333'
				        }, {
				          id: '12987123',
				          name: '好滋好味鸡蛋仔',
				          category: '江浙小吃、小吃零食',
				          desc: '荷兰优质淡奶，奶香浓而不腻',
				          address: '上海市普陀区真北路',
				          shop: '王小虎夫妻店',
				          shopId: '10333'
				        },]
			}
		},
		created(){
			this.initData()
		},
		methods:{
			async initData(){
				this.city = await cityGuess()
			 return await getResturantsCount().then(res => {
				 if(res.status == 1){
					 this.count = res.count
					 this.getResturants()
				 }else{
					 throw new Error('获取数据失败');
				 }
				 
				 })
			     .catch(err => {
					 console.log(err,'获取数据失败')
				 })
			     
				 
			},
			async getResturants(){
				const {latitude, longitude} = this.city;
				await getResturants({latitude, longitude, offset: this.offset, limit: this.limit})
				.then(res => {
					this.tableData = [];
					res.forEach(item => {
						const tableData = {}
						tableData.name = item.name;
						tableData.address = item.address;
						tableData.description = item.description;
						tableData.id = item.id;
						tableData.phone = item.phone;
						tableData.rating = item.rating;
						tableData.recent_order_num = item.recent_order_num;
						tableData.category = item.category;
						tableData.image_path = item.image_path;
						this.tableData.push(tableData);
					})
				})
				.catch(err => {console.log(err)})
				
			},
			async querySearchAsync(queryString, cb) {
			    if (queryString) {
			        try{
			            const cityList = await searchplace(this.city.id, queryString);
			            if (cityList instanceof Array) {
			                cityList.map(item => {
			                    item.value = item.address;
			                    return item;
			                })
			                cb(cityList)
			            }
			        }catch(err){
			            console.log(err)
			        }
			    }
			},
			async getCategory(){
				return await foodCategory()
				.then(res => {res.forEach(item => {
					if(item.sub_categories.length){
						const addnew = {
							value:item.name,
							label:item.name,
							children: []
						}
						item.sub_categories.forEach((item,index) => {
							if(index == 0){
								return
							}
							addnew.children.push({
								value: item.name,
								label: item.name,
							})
						})
						this.categoryOptions.push(addnew)
					}
				})})
				.catch(err => console.log(err,'获取商铺种类失败'))
			},
			addFood(index,row){
				this.$router.push({path: 'addGoods', query: { restaurant_id: row.id }})
			},
			addressSelect(item){
				console.log(item)
			},
			//每页条数改变时触发 选择一页显示多少行
			     handleSizeChange(val) {
			         console.log(`每页 ${val} 条`);
			         this.currentPage = 1;
			         this.pageSize = val;
			     },
			     //当前页改变时触发 跳转其他页
			     handleCurrentChange(val) {
			         this.currentPage = val;
					 this.offset = (val - 1)*this.limit;
					 this.getResturants()
			     },
				 handleEdit(index, row) {
					 this.selectTable = row;
					 this.address.address = row.address
					 this.dialogFormVisible = true
					 this.selectedCategory = row.category[1] ? row.category.split('/') : row.category
					 console.log(this.selectTable,this.selectedCategory);
					 if(!this.categoryOptions.length){
						 this.getCategory()
					 }
					 
				         
				},
				async handleDelete(index, row) {
				         await deleteResturant(row.id).then(res => {
							 if(res.status == 1){
								 this.$message({
								     type: 'success',
								     message: '删除店铺成功'
								 });
								 this.tableData.splice(index, 1);
							 }else{
								 throw new Error(res.message)
							 }
						 }).catch(err => {
							 this.$message({
							     type: 'error',
							     message: err.message
							 });
						 })
				},
				async onSubmit() {
				        this.dialogFormVisible = false;
						Object.assign(this.selectTable,this.address)
						this.selectTable.category = this.selectedCategory.join('/');
						await updateResturant(this.selectTable).then(res => {
							if(res.status == 1){
								this.$message({
									type: 'success',
									message: '更新店铺信息成功'
								})
								this.getResturants()
							}else{
								this.$message({
								    type: 'error',
								    message: res.message
								});
							}
						}).catch(err => {
							console.log('更新餐馆信息失败',err);
						})
						
						
				},
				handleAvatarSuccess(res, file) {
				        if(res.status == 1){
							this.selectTable.image_path = res.image_path
						}else{
							this.$message.error('上传图片失败！');
						}
				},
				beforeAvatarUpload(file) {
				        const isRightType = (file.type === 'image/jpeg') || (file.type === 'image/png');
				        const isLt2M = file.size / 1024 / 1024 < 2;
				
				        if (!isRightType) {
				          this.$message.error('上传头像图片只能是 JPG 格式!');
				        }
				        if (!isLt2M) {
				          this.$message.error('上传头像图片大小不能超过 2MB!');
				        }
				        return isRightType && isLt2M;
				      }
		},
		components:{
			headerTop
		},
		
	}
</script>

<style lang="scss">
	.demo-table-expand {
	    font-size: 0;
	  }
	  .demo-table-expand label {
	    width: 90px;
	    color: #99a9bf;
	  }
	  .demo-table-expand .el-form-item {
	    margin-right: 0;
	    margin-bottom: 0;
	    width: 50%;
	  }
	  .el-form{
		  margin-left: 50px;
	  }
	   .avatar-uploader .el-upload {
	      border: 1px dashed #d9d9d9;
	      border-radius: 6px;
	      cursor: pointer;
	      position: relative;
	      overflow: hidden;
	    }
	    .avatar-uploader .el-upload:hover {
	      border-color: #409EFF;
	    }
	    .avatar-uploader-icon {
	      font-size: 28px;
	      color: #8c939d;
	      width: 120px;
	      height: 120px;
	      line-height: 120px;
	      text-align: center;
	    }
	    .avatar {
	      width: 120px;
	      height: 120px;
	      display: block;
	    }
</style>
